package com.gitee.huxing.course.conc.conc03.tool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc03.tool
 * @ClassName: SemaphoreDemo2
 * @Author: huxingmale
 * @DateTime: 2021-08-26 0:26
 */
public class SemaphoreDemo2 {

    private final static int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    semaphore.acquire(3);   // 获得全部许可，退化成串行执行
                    test(threadNum);
                    semaphore.release(3);   // 释放多个许可
                } catch (Exception ex){
                    ex.printStackTrace();
                }
            });
            exec.shutdown();
        }
    }

    private static void test(int threadNum) throws Exception{
        System.out.println("id:"+threadNum+","+Thread.currentThread().getName());
        Thread.sleep(1000L);
    }
}
